<template>
	<view>
		<view class="botcart">
			<view>
				已加购货品（{{cartJon.length}}件）
			</view>
			<view style="display: flex;" @click="delCartAll" v-if="cartJon.length>0">
				 <u-icon name="trash" size="20" color="#666666"></u-icon><text>清空购物车</text>
			</view>
		</view>
		<view style="width:100%;height:auto;overflow-y:auto;background: #f5f5f5;margin-bottom:180upx">
			<view style="padding:20upx;margin-top:20upx;background:#ffffff" 
			v-for="(item,index) in cartJon">
				<checkbox-group  @change="checkBoxData">
					<checkbox  color="green" value="cb" :checked="item.checked" @click="clickCheckParent(item)" />{{item.shopName}}
				</checkbox-group>
				<view style="border-top: 1px solid #f5f5f5;margin-top:10upx"></view>
				<view style="display:flex;justify-content: space-between;margin-top:20upx;" v-for="(it,idx) in item.disheorderCarts">
					<view style="display:flex;" >
						<checkbox-group @change="childBoxData">
							<checkbox  color="green" value="cm" :checked="it.checked" @click="clickCheckClid(it,index)"/>
						</checkbox-group>
						<view @click="goGoodsDetail(it.dishesId)" style="display:flex;">
							<image mode="aspectFit" v-if="it.restShopDishes.dimg" style="width:3rem;height:4rem;"  :src="uploadFilePath+it.restShopDishes.dimg"></image>
							<image mode="aspectFit" v-else style="width:3rem;height:4rem;"  :src="goodlog"></image>
							<view style="margin-left:20upx">
								<view style="font-weight:bold">{{it.restShopDishes.dname}}</view>
								<view style="margin-top:0.5rem;font-weight:bold">
									￥{{it.restShopDishes.dprice}}
								</view>
								<view>{{it.specsDesc}}</view>
							</view>
						</view>
					</view>
					<u-number-box 
					   v-model = "it.buyNum"
					>
						 <view slot="minus" class="minus" @click="updateCart(item,it,0)">
							<u-icon
								name="minus-circle"
								size="25"
							></u-icon>
						</view>
						<text
							slot="input"
							style="width: 50px;text-align: center;"
							class="input"
						>{{it.buyNum}}</text>
						<view slot="plus" class="plus" @click="updateCart(item,it,1)">
							<u-icon
								name="plus-circle-fill"
								color="#04743a"
								size="25"
							></u-icon>
						</view>
					</u-number-box>
				</view>
			</view>
		</view>
		<!-- #ifdef MP-WEIXIN -->
			<view class="jsdiv" style="bottom:10upx">
		<!-- #endif -->
		<!-- #ifndef MP-WEIXIN -->
			<view class="jsdiv" :style="cssActive">
		<!-- #endif -->
			<view style="display: flex;padding-left:20upx;align-items: center;">
				<view style="position: relative;width:40px;height:40px">
					<u-badge type="error" shape="circle" max="99" :value="jbnum" class="jbcss"></u-badge>
					<image :src="bcart" style="width:80upx;height:80upx;position:absolute;z-index:1"></image>
				</view>
				
				<view style="margin-left:20upx;margin-left:20upx">
					<view>合计 <text style="font-size:16px;font-weight: bold;">￥{{sumMony}}</text></view>
					<!-- <view>优惠￥5</view> -->
				</view>
			</view>
			<view class="jxbtn" @click="goChangePayWay()">去结算</view>
		</view>
		<u-popup :show="showPay" mode="bottom" :round="10" @close="closePay">
			<view style="padding:10px;">
				<view style="text-align: center;">
					实付金额
				</view>
				<view style="text-align: center;font-size:1.2rem">￥{{sumMony}}</view>
				<view style="margin:10px 0px">选择支付方式:</view>
				<view>
					<radio-group @change="radioChange">
						<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in payWayxcx" :key="item.value">
							<view style="display:flex;justify-items: center;">
								<img :src="item.imgurl" style="width:60upx;height:60upx"/>
								<view style="line-height:60upx;height:60upx;padding-left:5px">{{item.label}}</view>
							</view>
							<view>
								<radio :value="item.value" :checked="item.state" />
							</view>
						</label>
					</radio-group>					
					<u-button type="primary" size="large" @click="addCartData">立即支付</u-button>										
				</view>
			</view>
		</u-popup>
		<u-modal :show="show" :title="title" :content='content'></u-modal>
		<u-modal :show="delState" :title="dtitle" @confirm="clearCart" @cancel="closeMd" :content='content' showConfirmButton showCancelButton></u-modal>
	</view>
</template>

<script>
	import Config from '@/util/index.js'
	import {
	 saveCart,updataCart,delCart,cartList,cartListOdr,cartListOdrPut,redayPay,redayxcxPay,cardxcxPay
	} from '@/api/cart'
	import {
	 getwxOpenId
	} from '@/api/user'
	export default {
		data() {
			return {
				activebar: 1,
				cart: [],
				cssActive:{},
				current:0,
				otml:'',
				bcart:'',
				formPas:{},
				goodlog:'',
				payWay:0,
				sgPay:false,
				payWayxcx:[
					{
					  imgurl:"../../../static/images/wxlog.jpeg",
					  value:'0',
					  label:'微信支付',
					  state:true
					},
					{
					  imgurl:"../../../static/images/cardlog.png",
					  value:'1',
					  label:'卡支付',
					  state:false
					}
				],
				  payWays:[
					    {
						  imgurl:"../../../static/images/wxlog.jpeg",
						  value:'0',
						  label:'微信支付',
						  state:true
					    },
					    {
						  imgurl:"../../../static/images/zfblog.png",
						  value:'2',
						  label:'支付宝支付',
						  state:false
					    }
				  ],
				  oneshopsum:0,
				  shopCheck:[],
				  dishesCheck:[],
				  ocartId:'',
				  showPay:false,
				  checkData:[],
				  storeState:true,
				  show:false,
				  title:'',
				  jbnum:0,
				  buyNum:1,
				  checkedData:[],
				  allChecked: false,
				  moreData:false,
				  totalPrice: 0,
				  totalNum: 0,
				  openid:'',
				  content:'',
				  mid:'',
				  ACCESS_TOKEN:'',
				  query: ['忌口',''], 
				  searchList:[{
					type: 'checkbox',
					screenKey: '常见忌口',
					screenValue: ['微辣','少盐','不要辣椒','不要香菜']
				}],
				  godsprice:'',
				  showkw:false,
				  cartnum:0,
				  total:0,
				  sumMony:0,
				  pageNum:1,
				  pageSize:10,
				  yqdes:'',
				  noData:false,
				  parentChecked:true,
				  //商品列表数据
				  list: [],
				  cartJon:[],
				  shopId:'',
				  content:'是否清空购物车',
				  dtitle:'清空购物车',
				  specData:[],
				  checkSpec:'',
				  dishesname:'',
				  rcode:'',
				  hasUserInfo:false,
				  userInfo:{},
				  scode:'',
				  orderState:'1',
				  orderId:'',
				  boxVals:[],
				  rowData:{},
				  checkData:[],
				  cartData:[],
				  checkIdData:[],
				  checked:true,
				  delState:false,
				  parentCheckState:false,
				  childCheckState:false,
				  uploadFilePath:''
			}
		},
		onReachBottom(){
			this.pageNum++
			this.getAllCart()
		},
		onLoad(options) {
		    // this.getSearchItems()
		    this.userId = uni.getStorageSync('userId')
			this.goodlog = this.picUrl + 'goods.png'
			this.bcart = this.picUrl + 'bcart.png'
			let _this = this
			uni.getStorage({
				key: 'deptdas',
				success: function (res) {
					let depts = JSON.parse(res.data)
					_this.scode = depts.scode
					_this.rcode = depts.rcode			
				}
			})
			
			// #ifdef MP-WEIXIN
				this.cssActive = {
					bottom:'10upx'
				}
			// #endif
			// #ifndef MP-WEIXIN
				this.cssActive = {
					bottom:'110upx'
				}
			// #endif
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {
			this.uploadFilePath = Config.get('apiUrl')
		    this.getAllCart()
		},
		methods:{
			goGoodsDetail(id){
				console.log(id)
				uni.navigateTo({
					url:`../goods/detail?gid=${id}`
				})
			},
			updataOrderState(){
				this.formPas.ostate = 1
				cartListOdrPut(this.formPas).catch(resp=>{
					uni.navigateTo({
						 url:'../my/order/index'
					})
				})
			},
			getOpenid(cdos){
				let params = {
					code:cdos,
					userId:this.userId
				}
				let _this = this
				getwxOpenId(params).catch(resp=>{
					let pars = {
						orderNumber:this.orderId,
						openId:resp.data.openid
					}
					redayxcxPay(pars).catch(resp=>{
						  //调用微信官方支付接口弹出付款界面,输入密码扣款
						wx.requestPayment({
						     timeStamp:resp.data.timeStamp,  //时间戳
						     nonceStr:resp.data.nonceStr,   //随机字符串
						     package:resp.data.package,    //prepay_id
						     signType:resp.data.signType,   //签名算法MD5
						     paySign:resp.data.paySign,    //签名
						     success (res) {
								 console.log("res32123",res)
						       if (res.errMsg == "requestPayment:ok"){
								  uni.showToast({
								    title:"支付成功",
								    icon: 'none',
								    duration: 2000
								  });
								  _this.showPay = false
								  //_this.updataOrderState()
						       }else{
								  uni.showToast({
								    title:"支付失败",
								    icon: 'none',
								    duration: 2000
								  });
						       }
						     },
						     fail (res) { 
							   uni.showToast({
							     title:"已取消支付",
							     icon: 'none',
							     duration: 2000
							   });
							    _this.showPay = false
							   //取消支付，购物车里的商品不做删除
							   // _this.getAllCart()
						     },
							 complete(res){
								  console.log("789",res)
							 }
						})
					})
				})
			},
			closeMd(){
				this.delState = false
			},
			radioChange(val){
				this.payWay = val.detail.value
			},
			closegoPay(){
				this.sgPay = false
			},
			pad(num) { return num.toString().padStart(2, '0')},
			formatDateTimeDay(date) {
			  const year = date.getFullYear();
			  const month = date.getMonth() + 1;
			  const day = date.getDate();
			  return `${year}-${this.pad(month)}-${this.pad(day)}`;
			},
			goPay(){
				let _this = this
				// #ifdef H5
				// h5端
					let params1 = {
						orderId:this.orderId
					}
					redayPay(params1).catch(resp=>{
						window.location.href = resp.data
					})
				// #endif
				
				// #ifdef APP-PLUS
				// app端
					let params = {
						orderId:this.orderId
					}
					redayPay(params).catch(resp=>{
						plus.runtime.openURL(resp.data, function(res) {  
						   console.log(res);  
					    });
					})
				// #endif
			},
			//去结算
			goChangePayWay(){
				this.showPay = true
			},
			addCartData(){
				if(this.shopId == "" || this.shopId == null){
					return uni.showToast({
						title:"请先选择要结算的商品",
						icon: 'none',
						duration: 2000
					});
				}
				let params = {
					orderId:"",
					userId:this.userId,
					pickupFlag:"0",
					ostate:0,//支付状态
					lstate:'0',//结算状态								
					shopId:this.shopId,
					endTime:'',//完成时间
					paymoney:0,//实付金额
					originalPrice:0,//原价
					ltime:"",//结算时间
					disheorderOrderitems:[]
				}
				let checkedSum = 0
				let math = require('mathjs');
				this.cartJon.forEach(its=>{
					its.disheorderCarts.forEach(itm=>{
						if(itm.checked){
							checkedSum++
							let obj = {
								itemId:'',
								ordId:'',
								dishesId:itm.dishesId,
								speId:itm.speIds,
								buyNum:itm.buyNum,
								memo:'',
								idisPrice:itm.dprice,//基础价格
								addPrice:itm.dprice,//规格加价
								ipayNum:itm.dprice*itm.buyNum,
								isflag:1
							}
								
							let stoal = 0
							let namss = []
							params.originalPrice+=itm.dprice*itm.buyNum	
							if(itm.specsDesc){									
								let arr = itm.specsDesc.split(";")
								for(let i=0;i<arr.length;i++){
									let arr2 = arr[i].split(',')
									let dx = arr2[0].indexOf(":")
									let nax = arr2[0].substr(dx+1)
									if(nax){
										namss.push(nax)
									}
									let result = arr2[arr2.length-1]
									if(result>0){
										stoal =  math.add(stoal,result)
										itm.dprice += math.add(itm.dprice,result)
									}
								}
								obj.speName = namss.toString()
							}
							obj.addPrice = stoal
							params.paymoney += math.multiply(itm.dprice,itm.buyNum)
							params.disheorderOrderitems.push(obj)
						}
					})
				})
				if(checkedSum==0){
					return uni.showToast({
						title:"请先选择要结算的商品",
						icon: 'none',
						duration: 2000
					});
				}
				this.formPas = params
				cartListOdr(params).catch(resp=>{										
					this.orderId = resp.data.data
					this.formPas.orderId = this.orderId
					// #ifdef MP-WEIXIN
					if(this.payWay==1){
						//卡支付
						let psx = {
							userId:this.userId,
							orderId:this.orderId
						}
						cardxcxPay(psx).catch(respz=>{	
							console.log("respz",respz)
							if(respz.data.code==200){
								uni.navigateTo({
									 url:'../my/order/index'
								})
							}
						})
					}else{
						uni.login({
							provider: 'weixin',
							success: res => {
								if (res.code) {
									// 获取到登录凭证code
									let code = res.code;
									// 调用后端接口，传递code进行获取openid操作
									this.getOpenid(code)
								}
							}
						});
					}
					
					// #endif
					// #ifndef MP-WEIXIN
						this.showPay = true
					// #endif
				})
			},
			goGoodsDe(data){
				// this.$navTo(`./goods/detail`, { goodsId })
				uni.navigateTo({
					url: `goods/detail?gid=${data.dishesId}`
				})
			},
			childBoxData(item){
				let arr = item.detail.value
				if(arr[0]){
					//选中
					this.childCheckState = true
				}else{
					//取消选中
					this.childCheckState = false
				}
			},
			clickCheckClid(item,idx){
				console.log("xsss",item)
				let num = 0
				this.cartJon[idx].disheorderCarts.forEach(it=>{
					if(it.checked==true){
						num++
					}
				})
				let clen = this.cartJon[idx].disheorderCarts.length
				if(num==clen){
					this.cartJon[idx].checked = true
				}
				let math = require("mathjs")
				let sum = 0
				let stoal = 0
				let gprice = 0
				if(this.childCheckState){
					console.log("item.buyNum",item.buyNum)
					item.checked = true
					this.shopId = this.cartJon[idx].shopId
					if(item.specsDesc){
						let arr = item.specsDesc.split(";")
						for(let i=0;i<arr.length;i++){
							let arr2 = arr[i].split(',')
							let result = arr2[arr2.length-1]
							if(result>0){
								stoal = math.add(stoal,result)
							}
						}
						gprice = math.add(stoal,item.dprice)
					}else{
						gprice = item.dprice
					}
					let gosm = math.multiply(gprice,item.buyNum)
					sum = math.add(this.sumMony,gosm)
					this.sumMony = math.round(sum,2)
				}else{
					item.checked = false
					this.cartJon[idx].checked = false
					if(item.specsDesc){
						let arr = item.specsDesc.split(";")
						for(let i=0;i<arr.length;i++){
							let arr2 = arr[i].split(',')
							let result = arr2[arr2.length-1]
							if(result>0){
								stoal = math.add(stoal,result)
							}
						}
					}
					let gprice = math.add(stoal,item.dprice)
					let gosm = math.multiply(gprice,item.buyNum)
					sum = math.subtract(this.sumMony,gosm)
					this.sumMony = math.round(sum,2)
					// this.$set(this.cartJon[idx], 'checked', false) 
				}
			},
			clickCheckParent(item){
				let basesum = 0
				let math = require("mathjs")
				if(this.parentCheckState){
					this.childCheckState = true
					item.checked = true
					this.shopId = item.shopId
					item.disheorderCarts.forEach(im=>{
						let stoal = 0
						im.checked = true
						basesum = math.multiply(im.dprice,im.buyNum) 
						if(im.specsDesc){
							let arr = im.specsDesc.split(";")
							for(let i=0;i<arr.length;i++){
								let arr2 = arr[i].split(',')
								let result = arr2[arr2.length-1]
								if(result>0){
									stoal = math.add(stoal,result)
								}
							}
						}
						this.oneshopsum += math.add(stoal,basesum)
					})
					this.sumMony = math.round(this.oneshopsum,2)
				}else{
					this.childCheckState = false
					item.checked = false
					item.disheorderCarts.forEach(im=>{
						im.checked = false
						let stoal = 0
						basesum = math.multiply(im.dprice,im.buyNum) 
						if(im.specsDesc){
							let arr = im.specsDesc.split(";")
							for(let i=0;i<arr.length;i++){
								let arr2 = arr[i].split(',')
								let result = arr2[arr2.length-1]
								if(result>0){
									stoal = math.add(stoal,result)
								}
							}
						}
						this.oneshopsum = math.round(math.add(stoal,basesum),2)
						this.sumMony = math.subtract(this.sumMony,this.oneshopsum)
					})
					this.sumMony = math.round(this.sumMony,2)
				}

				if(this.sumMony==0){
					this.oneshopsum = 0
				}
				this.cartJon = JSON.parse(JSON.stringify(this.cartJon))
			},
			checkBoxData(item){
				let arr = item.detail.value
				if(arr[0]){
					//选中
					this.parentCheckState = true
				}else{
					//取消选中
					this.parentCheckState = false
				}
			},
			clearCart(){
				this.boxVals = []
				this.cartJon.forEach((item)=>{
					item.disheorderCarts.forEach(itm=>{
						this.boxVals.push(itm.ocartId)
					})
				})
				let params = this.boxVals.join(",")
				delCart(params).catch(res => {
					if(res.data.code == 200){
						uni.showToast({
						  title:"删除成功",
						  icon: 'none',
						  duration: 2000
						});
						this.delState = false
						this.pageNum = 1
						this.sumMony = 0
						this.getAllCart()
					}
				})
			},
			delCartAll(row,cd){
				this.delState = true
			},
			updateCart(row,cd,num){
				let bunum = cd.buyNum
				if(num==1){
					bunum++
				}else{
					bunum--
				}
				if(bunum>0){
					//添加购物车
					let params = {
						ocartId:cd.ocartId,
						userId:this.userId,
						shopId:row.shopId,
						dishesId:cd.dishesId,
						dprice:cd.dprice,
						deptId:this.rcode,
						buyNum:bunum,
						speIds:cd.speIds,
						isflag:1
					}
					updataCart(params).catch(ress => {
						if(ress.code == 200){
							uni.showToast({
								title:"修改成功",
								icon: 'none',
								duration: 2000
							});
							console.log("2233")
							this.pageNum = 1
							this.sumMony = 0
							//直接加购物车
							this.getAllCart()
						}
					})
				}else{
					delCart(cd.ocartId).catch(res => {
						if(res.data.code == 200){
							uni.showToast({
							  title:"删除成功",
							  icon: 'none',
							  duration: 2000
							});
							this.pageNum = 1
							this.sumMony = 0
							this.getAllCart()
						}
					})
				}
			},
			getAllCart(){
				if(this.pageNum==1){
					this.cartJon = []
				}
				let pas = {
					userId:this.userId,
					pageNum:this.pageNum,
					deptId:this.rcode,
					pageSize:this.pageSize
				}
				cartList(pas).catch(resp => {
					if(resp.data.cart.length > 0){
						this.cartJon = resp.data.cart
						// resp.data.cart.forEach(item=>{
						// 	let stoal = 0
						// 	let namss = []
						// 	let math = require('mathjs');
						// 	if(item.specsDesc){									
						// 		let arr = item.specsDesc.split(";")
						// 		for(let i=0;i<arr.length;i++){
						// 			let arr2 = arr[i].split(',')
						// 			let dx = arr2[0].indexOf(":")
						// 			let nax = arr2[0].substr(dx+1)
						// 			if(nax){
						// 				namss.push(nax)
						// 			}
						// 			if(arr2[arr2.length-1]){
						// 				stoal = math.add(stoal,arr2[arr2.length-1])
						// 			}
						// 		}
						// 	}
						// 	this.sumMony += math.add(stoal,math.multiply(item.dprice,item.buyNum)) 
						// })
						// this.sumMony = math.round(this.sumMony,2)
					}else{
						if(this.pageNum==0){
						  this.noData = true
						}
						this.moreData = true
						uni.showToast({
						  title:"暂无数据",
						  icon: 'none',
						  duration: 2000
						});
					}
				})
			},
			  onChangearea(e){
			    this.yqdes = e.detail
			  },
			  // 获取搜索选项
			  getSearchItems() {
			    const _this = this
			    // 异步请求数据后处理，这里直接拿假数据
			    const searchItems = this.searchList.map(n => {
			      return Object.assign({}, n, {
			        screenValue: n.screenValue.map(m =>
			          Object.assign(
			            {},
			            {
			              checked: _this.query.includes(m), // 回显query里有返回true
			              value: m
			            }
			          )
			        )
			      })
			    })
			    this.searchList = searchItems
			  },
			  onChangekw(e){
			    const { parentIndex, item, index } = e.currentTarget.dataset
			    // 如果选中状态
			    if (item.screenValue[index].checked) {
			      item.screenValue[index].checked = false // 取消选择
			    } else {
			      // 如果不是多选
			      if (item.type != 'checkbox') {
			        // 全部重置为未选择状态
			        item.screenValue.map(n => (n.checked = false))
			      }
			      // 将点击的设置为选中
			      item.screenValue[index].checked = true
			    }
			    
			     this[`searchList[${parentIndex}]`] = item
			    
			  },
			    async getGoodsInfo(did){
			        let loginid = ""
			        let params = {
			          loginid:loginid,
			          dcode:did
			        }
			        let _this = this
			        return new Promise((resolve, reject) => {
			          var url = app.siteInfo.api.goodsDetail;
			          app.util.postData(url,params).then((res) => {
			            _this.setData({openid:res.dishes.openid,mid:res.dishes.mid})
			             resolve(res.dishes)
			          }).catch((err) => {
			              console.error(err)
			              reject(err)
			          })
			        })
			      },
			    onClose(){
			      this.showkw = false
			    },
			   goCreateOrder(){
			    let data = this.checkData
			    let selected = []
			    // 获取所有选中
			    this.searchList.map(n => {
			      n.screenValue.map(m => {
			        if (m.checked == true) {
			          selected.push(m.value)
			        }
			      })
			    })
			    let jikou = selected.toString()
			    if(this.yqdes){
			        this.memo = jikou+''+this.yqdes
			    }else{
			        this.memo=jikou
			    }
			    let userId = ""
			    // let index = cart.findIndex(v => v.mid === data[0].management.mid);
			    let params = {
			        dishes:data,
			        loginid:userId,
			        memo:this.memo
			    }
			    let _this = this
			    app.api.createOrder(params, function (res) {
			        params.orderId = res.qcode
			        uni.hideLoading()
			        _this.showkw=false
			        if(res.retCode == 0){
			            // Dialog.confirm({
			            //     title: '温馨提示',
			            //     message: `${res.info}\n折后金额:${res.折后金额}\n本单总金额:${res.本单总金额}`,
			            //   })
			            // .then(() => {
			                
			            // })
			            // .catch(() => {
			              
			            // });          
			          _this.removeBuyGoods(params)  
			        }else{
			            uni.showToast({
			                title:res.info,
			                icon: 'none',
			                duration: 2000
			            });
			        }
			    })
			  },
			  removeBuyGoods(data){
			    data.sum = this.data.totalPrice
			     //1获取购物车商品数组
			     let cart = this.data.cart;
			     //2.1筛选未选中的商品数组
			     cart = cart.filter(v => v.checked ? '' : v);
			     for(var i=0;i<cart.length;i++){
			         for(var j=0;j<cart[i].child.length;j++){
			             if(cart[i].checked){
			                 cart[i].splice(i,1)
			             }else{
			                 if(cart[i].child[j].checked){
			                     cart[i].child.splice(j,1)
			                 }
			             }
			         }
			     }
			     //2.2筛选好的数组重新进行赋值到data中
			     this.cart = cart
			         this.totalNum = 0
			     if(this.cart.length>0){
			         //2.3筛选好的数组重新上传到本地存储中
			         uni.setStorageSync("cart", cart);
			         this.setCart(cart)
			     }else{
			        this.totalPrice = 0
			        this.cart=[]
			        uni.setStorageSync("cart", cart);
			     }
			     uni.navigateTo({
			        url:'../student/gopay?cdata='+JSON.stringify(data)
			    })
			  },
			  onChangebar(event) {
			    this.activebar=event.detail;
			    uni.navigateTo({
			      url: this.list[event.detail]
			    })
			  },
			
			  //改变购物车数据和本地存储的购物车数据
			  setCart(cart) {
			      //全选按钮的状态
			      let allChecked = false;
			      //购物车商品的总价格
			      let totalPrice = 0;
			      //购物车商品的总数量
			      let totalNum = 0;
			      let parentCheckedNum = 0;
			    //   let childCheckedNum = 0;
			      for(let i=0;i<cart.length;i++){
			        if(cart[i].checked){
			            parentCheckedNum++
			        }
			        for(let j=0;j<cart[i].child.length;j++){
			            if (cart[i].child[j].checked) {
			                totalPrice +=cart[i].child[j].discount * cart[i].child[j].dprice;
			                totalNum += cart[i].child[j].discount
			                // childCheckedNum++;
			                // if(childCheckedNum==cart[i].child.length ){
			                //     cart[i].checked = true
			                // }
			            }
			        }
			      }
			      if(parentCheckedNum==cart.length ){
			        allChecked = true
			      }
			     //evert数组函数，当数组值所有的值都符合条件是返回true，否则返回false
			      this.cart = cart
			        this.totalPrice = totalPrice
			        this.totalNum = totalNum
			        this.allChecked = allChecked
			    //改变本地存储的购物车数据
			    // uni.setStorageSync("cart", cart);
			  },
			  handleParentChange(id){
			    //2.获取所有购物车数据
			    let cart = this.cart;
			    //3.获取商品的索引
			    let index = cart.findIndex(v => v.mid === id);
			    //4.将对应的购物车商品的checked属性取反
			    cart[index].checked = !cart[index].checked;
			    //4.调用封装好的函数setCart
			    if(cart[index].checked){
			        for(var i=0;i<cart[index].child.length;i++){
			            cart[index].child[i].checked = true
			        }
			        this.setCart(cart);
			    }else{
			        let cuur_goods_sum = 0;
			        for(let i=0;i<cart[index].child.length;i++){
			            cuur_goods_sum += cart[index].child[i].discount * cart[index].child[i].dprice;
			            cart[index].child[i].checked = false
			        }
			        let totalPrice = this.totalPrice - cuur_goods_sum
			        this.totalPrice = totalPrice
					this.cart = cart
					this.allChecked = false
			    }
			  },
			  //购物车车商品选中事件
			  handleItemChange(pid,cid,id) {
			    //1.获取商品的id
			    let pidx = pid;
			    let dcode = id;
			    let index = cid;
			    //2.获取所有购物车数据
			    let {
			        cart
			    } = this.data;
			    //3.获取商品的索引
			    //let idx = cart[pidx].child.findIndex(v => v.dcode === id);
			    cart[pidx].child[index].checked = !cart[pidx].child[index].checked;
			    //4.调用封装好的函数setCart
			    // this.setCart(cart);
			    if(cart[pidx].child[index].checked){
			        let checknum = 0;//选中数量
			        for(let i=0;i<cart[pidx].child.length;i++){
			            if (cart[pidx].child[i].checked) {
			                checknum++ 
			            }
			        }
			        if(checknum==cart[pidx].child.length){
			            cart[pidx].checked = true
			        }
			        this.setCart(cart);
			    }else{
			        let cuur_goods_sum = cart[pidx].child[index].discount * cart[pidx].child[index].dprice;
			        this.totalPrice=this.data.totalPrice-cuur_goods_sum
					this.allChecked = false
			        cart[pidx].checked = false
			        this.cart = cart
			    }
			    
			  },
			  //底部工具栏全选事件
			  handleItemAllChange() {
			      //1.获取data中的数据
			      let {
			          cart,
			          allChecked
			      } = this.data;
			      //2.将allChecked取反
			      allChecked = !allChecked;
			      //3.将cart中的checked属性全部等于allChecked
			      if(allChecked){
			          let cuur_goods_sum = 0;
			        for(let i=0;i<cart.length;i++){
			            cart[i].checked = true
			            for(let j=0;j<cart[i].child.length;j++){
			                cart[i].child[j].checked = true
			                cuur_goods_sum += cart[i].child[j].discount * cart[i].child[j].dprice;
			            }
			        }
			        this.cart = cart
					this.totalPrice = cuur_goods_sum
					this.allChecked = allChecked
			        // this.setCart(cart);
			      }else{
			        for(let i=0;i<cart.length;i++){
			            cart[i].checked = false
			            for(let j=0;j<cart[i].child.length;j++){
			                cart[i].child[j].checked = false
			            }
			        }
					this.cart = cart
					this.totalPrice = 0
					this.allChecked = allChecked
			      }
			      //4.调用封装好的函数setCart
			    //   this.setCart(cart)
			  },
			  //商品数量的加减
			  async handleEdit(pIndex,index,oid,pid,did) {
			      //1.获取商品的id和operation
			      let id = did
				let parentIndex = pIndex
				let operation = oid
			      //2.获取data中的cart数据
			      let {
			          cart
			      } = this.data;
			      //3.获取点击事件的索引
			      let idex = cart[pIndex].child.findIndex(v => v.dcode === did)
			          //4.对商品的数量进行加减
			      if (cart[pIndex].child[idex].discount == 1 && operation === -1) {
			          //5.当商品数量等于1时，而且是进行减少操作时，弹出模态框，判断是否要删除商品
			          //showModel是封装成promise的uni.showModel的api
			          const res = await showModel({
			              content: '你确定要删除该商品吗？'
			          });
			          //在模态框中点击确认，删除购物车中的该商品数据
			          if (res.confirm) {
			              if(cart[pIndex].child.length==1){
			                cart.splice(pIndex, 1); 
			              }else{
			                cart[pIndex].child.splice(index, 1);
			              }
			             //2.2筛选好的数组重新进行赋值到data中
			             this.cart = cart
			            this.totalNum = totalNum
			             if(this.cart.length>0){
			                 //2.3筛选好的数组重新上传到本地存储中
			                 uni.setStorageSync("cart", cart);
			                //  _this.setCart(cart)
			             }else{
			                 this.totalPrice=0
			             }
			              this.setCart(cart);
			              //弹出提示删除成功
			              await uni.showToast({
			                  title: "删除成功"
			              })
			          } else {
			              //取消删除
			              //弹出提示取消删除
			              await uni.showToast({
			                  title: "取消删除"
			              })
			          }
			      } else {
			          //6.商品数量大于1或是商品是进行增加操作时，正常进行
			          cart[parentIndex].child[idex].discount += operation;
			          this.setCart(cart);
			      }
			  },
			  //删除选中的商品
			  async handelDelChecked() {
			      //1获取购物车商品数组
			      let cart = this.cart;
			      //2.判断购物车数组是否有选中的商品
			        const res = await showModel({
			            content: '你确定要清空购物车吗？'
			        })
			        //2.判断是否确定要删除选中的商品
			        if (res.confirm) {
			            //2.1筛选未选中的商品数组
			            this.cart=[]
						this.totalPrice=0
			            uni.setStorageSync("cart",[]);
			            //2.4弹出提示删除成功
			            await uni.showToast({
			                title: "删除成功"
			            })
			        } else {
			            //取消删除
			            //弹出提示取消删除
			            await uni.showToast({
			                title: "取消删除"
			            })
			        }
			  },
			  closePay(){
				  this.showPay = false
			  },
			  isRepeat(midArr){
			    if (Array.isArray(midArr)) {
			         return new Set(midArr).size === 1;
			    }
			    return false;
			 }
		}
	}
</script>

<style>
    .jsdiv{
		width:90%;height:100upx;border-radius: 50px;border:1px solid #f5f5f5;box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5);display: flex;justify-content: space-between;
		margin:20upx 30upx;position: fixed;background:#fff
	}
	.jbcss{width:15upx;margin-left:30px;position:absolute;z-index: 10;}
	.botcart{height:60upx;line-height:60upx;padding:20upx;display:flex;justify-content: space-between;border-bottom:1px solid #f5f5f5}
	.jxbtn{width:150upx;height:100upx;font-size:18px;line-height:100upx;text-align: center;
	background-color:#04743a;color:#fff;border-top-right-radius: 50px;border-bottom-right-radius: 50px;}
	.uni-list-cell{display:flex;justify-items: center;justify-content: space-between;margin:10px 0px}
	.utag{width:auto;height:1rem;border: 1px solid #F66;font-size: 0.8rem;padding:0.2rem;border-radius: 10px;margin-right:0.5rem}
</style>
